package com.app.songbump;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import android.app.ListActivity;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.media.MediaMetadataRetriever;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

public class SongBumpMusicActivity extends ListActivity {
	AppPreferences appPrefs;

	private static final String MEDIA_PATH = new String("/sdcard/Music/");
	private List<String> songs = new ArrayList<String>();
	private MediaPlayer mp = new MediaPlayer();
	private int currentPosition = 0;
	BroadcastAudio ba;
	String myIp;
	private Button prevButton;
	private Button nextButton;
	private Button playButton;

	private TextView trackInfo;
	private MediaMetadataRetriever mmr = new MediaMetadataRetriever();

	int initialPlay = 1;
	String songName;
	String artist;
	String uid;
	String songPath;
	
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		
		Bundle b = getIntent().getExtras();
	    myIp = b.getString("ip");
	    
		super.onCreate(savedInstanceState);
		setContentView(R.layout.player);
		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
		appPrefs = new AppPreferences(getApplicationContext());
		
		prevButton = (Button) this.findViewById(R.id.prev);
		playButton = (Button) this.findViewById(R.id.play);
		nextButton = (Button) this.findViewById(R.id.next);

		// Buttons are disabled until there are songs on the device
		prevButton.setEnabled(false);
		playButton.setEnabled(false);
		nextButton.setEnabled(false);
		trackInfo = (TextView) this.findViewById(R.id.currentTrack);

		accessMusicLibrary();
		uid = appPrefs.getUserId();
		prevButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				prevSong();
			}
		});

		nextButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				nextSong();
			}
		});

		playButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				doPlay();
			}
		});
	}

	private void doPlay() {

		// Already playing a song so pause
		if (mp.isPlaying()) {
			playButton.setText("Play");
			mp.pause();
		}
		// Not playing a song, so start playing
		else {
			if (initialPlay == 1) {
				initialPlay = 0;

				Intent msgIntent = new Intent(SongBumpMusicActivity.this, SongBumpServer.class);
				msgIntent.putExtra(SongBumpServer.ACTION,SongBumpServer.NEW_SONG);
				msgIntent.putExtra("id",uid);
				msgIntent.putExtra("artist",artist);
				msgIntent.putExtra("title",songName);
				msgIntent.putExtra("ip",myIp);
				startService(msgIntent);
				
				//This is the code to stream music
				Log.v("new broadcast object", songPath);
				if (ba != null){
					ba.setSong(songPath);
				} else {
					ba = new BroadcastAudio(songPath, this.getApplicationContext(), myIp);
				}
				
			}
			mp.start();
			playButton.setText("Pause");

		}

	}

	private void initSongInPlayer() {
		try {

			songPath = MEDIA_PATH + songs.get(currentPosition);
			mp.reset();
			mp.setDataSource(songPath);
			mp.prepare();
			
			mmr.setDataSource(songPath);
			
			// Set currently playing track info
			songName = mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_TITLE);
			artist = mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ARTIST);
			trackInfo.setText("Title: " + songName + "\n Artist: " + artist);
			doPlay();
			// Setup listener so next song starts automatically
			mp.setOnCompletionListener(new OnCompletionListener() {

				public void onCompletion(MediaPlayer arg0) {
					nextSong();
				}
			});

		} catch (IOException e) {
			Log.v(getString(R.string.app_name), e.getMessage());
		}
	}

	private void nextSong() {
		// Move forward one position in queue
		if (++currentPosition >= songs.size())
			// Last song so reset currentPosition to first song
			currentPosition = 0;
		initialPlay = 1;
		initSongInPlayer();
	}

	private void prevSong() {
		// Move back one position in song queue
		if (--currentPosition < 0) // If negative, go to last song
			currentPosition = songs.size() - 1;
		initialPlay = 1;
		initSongInPlayer();
	}

	private void accessMusicLibrary() {
		File home = new File(MEDIA_PATH);
		if (home.listFiles(new Mp3Filter()).length > 0) {
			for (File file : home.listFiles(new Mp3Filter())) {
				songs.add(file.getName());
			}
			ArrayAdapter<String> songList = new ArrayAdapter<String>(this,
					R.layout.list_item, songs);
			setListAdapter(songList);

		}
		if (!songs.isEmpty()) {
			initSongInPlayer();
			prevButton.setEnabled(true);
			playButton.setEnabled(true);
			nextButton.setEnabled(true);
		}
	}

	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		if (currentPosition != position) {
			currentPosition = position;
			initialPlay = 1;
			initSongInPlayer();
		}
	}
	@Override
	public void onStart() {
		super.onStart();
		//initSongInPlayer();
	}
	@Override
	public void onStop() {
		super.onStop();
		Intent msgIntent = new Intent(SongBumpMusicActivity.this, SongBumpServer.class);
		msgIntent.putExtra(SongBumpServer.ACTION,SongBumpServer.NOTHING_PLAYING);
		msgIntent.putExtra("id",uid);
		startService(msgIntent);
	}
	
}
